<?php


namespace app\api\controller;


use app\BaseController;
use app\lib\exception\BaseException;
use app\model\Users;
use dh2y\qrcode\QRcode;

class Login extends BaseController
{
    public function index()
    {
        (new \app\validate\Login())->goCheck();
        $params = request()->param();
        $user = Users::where('mobile', $params['mobile'])->find();
        if (!$user) throw new BaseException(['msg' => '账号或密码错误！', 'errorCode' => 400]);
        if (!password_verify($params['password'], $user->password)) throw new BaseException(['msg' => '账号或密码错误！']);
        if($user->status==0) throw new BaseException(['msg' => '该账号已被禁用，请联系管理员！']);
        $token=createToken($user->id);
        return $this->success(['token'=>$token]);
    }

    public function apple()
    {
        $params = request()->param();
        $user=Users::where('apple_id',$params['apple_id'])->find();
        if(!$user){
           $apple= Users::create($params);
            $code=new QRcode();
            $filePath =$code->png('用戶ID：'.$apple->id,false, 6)->getPath(false);
            Users::where('id',$apple->id)->update(['qrcode'=>ossUpload($filePath)]);
           return $this->success(['token'=>createToken($apple->id)]);
        }
        return $this->success(['token'=>createToken($user->id)]);
    }

    public function facebook()
    {
        $params = request()->param();
        $user=Users::where('facebook_id',$params['facebook_id'])->find();

        if(!$user){
            $apple= Users::create($params);
            $code=new QRcode();
            $filePath =$code->png('用戶ID：'.$apple->id,false, 6)->getPath(false);
            Users::where('id',$user->id)->update(['qrcode'=>ossUpload($filePath)]);

            return $this->success(['token'=>createToken($apple->id)]);
        }
        return $this->success(['token'=>createToken($user->id)]);
    }

    public function google()
    {
        $params = request()->param();
        $user=Users::where('google_id',$params['google_id'])->find();
        if(!$user){
            $apple= Users::create($params);
            $code=new QRcode();
            $filePath =$code->png('用戶ID：'.$apple->id,false, 6)->getPath(false);
            Users::where('id',$user->id)->update(['qrcode'=>ossUpload($filePath)]);
            return $this->success(['token'=>createToken($apple->id)]);
        }
        return $this->success(['token'=>createToken($user->id)]);
    }
}